package com.sqk.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.sqk.reggie.common.BaseContext;
import com.sqk.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//import jakarta.servlet.*;
//import jakarta.servlet.annotation.WebFilter;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;

@Slf4j
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符(由spring提供)
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setCharacterEncoding("UTF-8");  //POST 请求时有效

        //1.获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("以拦截 {}",requestURI);

        //定义不需要拦截的路径(即:登录，退出，静态资源等)
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        /*//拦截地址请求
        if (antPathMatcher.match("/address-edit.html",requestURI)){
            response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
            return;
        }*/

        //2.判断是否是不需要拦截的路径
        Boolean notCheck = checkPath(urls, requestURI);
        if(notCheck){
            log.info("本次请求 {} 不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //3-1.判断员工是否登录。(即:在访问其他操作页面时，是否为登录状态，是:放行，否:跳转登录页面)
        //用session判断
        if(null != request.getSession().getAttribute("employee")){

            //ThreadLocal设置当前登录员工id
            Long emplId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(emplId);

            //说名以登陆
            filterChain.doFilter(request,response);
            return;
        }

        //3-2.判断用户是否登录。(即:在访问其他操作页面时，是否为登录状态，是:放行，否:跳转登录页面)
        //用session判断
        if(null != request.getSession().getAttribute("user")){

            //ThreadLocal设置当前登录员工id
            String userPhone = (String) request.getSession().getAttribute("user");
            log.info("userPhone = {}",userPhone);
            Long userId =Long.parseLong(userPhone);
            BaseContext.setCurrentId(userId);

            //说名以登陆
            filterChain.doFilter(request,response);
            return;
        }

        log.info("登录失败 ");
        //4.未登录，跳转登录页面，(因跳转操作在前端文件中完成，所以这里只需要传递数据)
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }

    public Boolean checkPath(String[] urls,String requestUrl){
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestUrl);
            if(match){
                return true;
            }
        }
        return false;
    }
}
